package org.example.netty.zdyxieyi;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ServerDemo {
    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(1024,14,4,0,0));
                        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                        pipeline.addLast(new MessageCodec());
                        pipeline.addLast(new SimpleChannelInboundHandler<Message>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, Message message) throws Exception {
                                log.info("message:{}",message);
                                channelHandlerContext.fireChannelRead(message);
                            }
                        });
                        pipeline.addLast(new SimpleChannelInboundHandler<Message>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, Message message) throws Exception {
                                log.info("message2222:{}",message);
                                if(message.getMessageType()==1){
                                    channelHandlerContext.writeAndFlush(new LoginResponseMessage(true,"ok"));
                                }else{
                                    for (int i = 0; i < 10; i++) {
                                        channelHandlerContext.writeAndFlush(new LoginResponseMessage(true,"54454545"));
                                    }
                                }
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
